'use strict';
/**
 * create a controller with a standard REST interface
 * /name/:id (get)
 * /name/ (post) (protect)
 * /name/ (put) (protect)
 * /name/:deleteId (delete) (protect)
 */
var path = require('path');
var util = require('util');
var yeoman = require('yeoman-generator');
var _ = require('underscore');
var ScriptBase = require('../../lib/script-base.js');
var stocks = {
    'create': {
        listen: 'post',
        protect: true
    },
    'read': {
        listen: 'get',
        param: 'id'
    },
    'update': {
        listen: 'put',
        protect: true,
        param: 'updateId' // to prevent the object to string lost one part
    },
    'delete': {
        listen: 'delete',
        protect: true,
        param: 'deleteId'
    }
};

/**
 * constructor
 */
var Generator = module.exports = function()
{
    yeoman.generators.NamedBase.apply(this, arguments);
    this.sourceRoot(path.join(__dirname, path.join('..','templates','common','app','server','controllers')));

    if (!this.env.options.appPath) {
        this.env.options.appPath = path.join('.','app','server','controllers');
    }
    this.scriptSuffix = '.js';
    var config = this.getPanesConfig();

    if (!config) {
        var err = (this.lang==='cn') ? '' : 'Your installation might have been corrupted. Can not retrieve your original setup!';
        this.log.error(err);
        throw err;
    }
    else {
        this.lang = config['lang'];
    }
    // allow interactive mode
    if (this.interactive) {
        this.actions = {};
    }
};

/**
 * extending
 */
util.inherits(Generator, ScriptBase);

/**
 * this will generate a stock rest api
 */
Generator.prototype.generateStockREST = function(protectAll)
{
    var _this = this;
    var routes = {};
    var actionDef = [];
    var controller = this.name;
    _.each(stocks , function(def , action)
    {
        var d = {controller: controller , action: action , listen:  def.listen};
        if (def.protect) {
            d.protect = 'true';
        }
        var r = '/' + controller + (def.param ? '/:' + def.param : '');
        routes[r] = d;

        // controller file
        var _def = '';

        _def = '\t\'' + action + '\': {\n';
        if (def.param) {
            _def += '\t\tparam: \'' + def.param + '\',\n';
        }
        if (def.protect) {
            _def += '\t\tprotect: true,\n';
        }
        _def += '\t\tlisten: \'' + def.listen +'\',\n';
        _def += '\t\taction: function(req , res) {\n';
        _def += '\t\t\tthis.set({text: \'Hello\'});\n';
        _def += '\t\t}\n\t}';
        actionDef.push(_def);
    });

    this.actionDef = actionDef.join(',\n');
    // this.helloWorld = this.name;
    this.appTemplate(
        'interactive',
        this.name,
        '.ctrl' + this.scriptSuffix
    );
    // writing to the route
    this.generateNewRoute(routes);
};
